/**
 * Main JavaScript
 *
 * Copyright (c) 2013. by Way2CU
 * Author: Mladen Mijatov
 */

$(function() {
	var overlay = $('div.overlay');
	var backend_url = $('base').attr('href') + '/index.php';

	// create and configure dialog for notifying user about form submission
	var dialog = new Dialog();
	var dialog_message = $('<div>');

	dialog.setSize(350, 100);
	dialog.setContent(dialog_message);
	dialog_message.css('padding', '20px');

	// preload contact form messages
	var message_list = ['dialog_title', 'message_fields', 'message_thank_you', 'message_error'];
	language_handler.getTextArrayAsync(null, message_list, function() {
			// set dialog title after messages are done loading
			dialog.setTitle(language_handler.getText(null, 'dialog_title'));
		});

	// handle form submission
	$('div#contact_form form').submit(function(event) {
		// prevent default form behavior
		event.preventDefault();

		// collect data
		var empty_fields = 0;
		var data = {
				section: 'survey',
				action: 'save_from_ajax',
				type: 'contact_form'
			};

		$(this).find('input').each(function() {
			var name = $(this).attr('name');
			var value = $(this).val();

			if (value.trim() == '')
				empty_fields++; else
				data[name] = value;
		});

		// if some of the fields were omitted, show error
		if (empty_fields > 0) {
			dialog.setError(true);
			dialog_message.html(language_handler.getText(null, 'message_fields'));
			dialog.show();

			return true;
		}

		// show overlay
		overlay.css({display: 'block', opacity: 0}).animate({opacity: 1}, 300);

		// send data to server
		$.ajax({
			url: backend_url,
			cache: false,
			context: this,
			dataType: 'json',
			type: 'GET',
			data: data,
			success: function(data) {
				// show form again
				overlay.animate({opacity: 0}, 300, function() {
						$(this).css('display', 'none');
					});

				if (data) {
					// prepare dialog
					dialog.setError(false);
					dialog_message.html(language_handler.getText(null, 'message_thank_you'));
					dialog.show();

				} else {
					// there was an error processing request, show message
					dialog.setError(true);
					dialog_message.html(language_handler.getText(null, 'message_error'));
					dialog.show();
				}
			},
			error: function(xhr, status, error) {
				// show form again
				overlay.animate({opacity: 0}, 300, function() {
						$(this).css('display', 'none');
					});

				// there was an error processing request, show message
				dialog.setError(true);
				dialog_message.html(language_handler.getText(null, 'message_error'));
				dialog.show();
			}
		});
	});
});
